package com.hcb.tonguetiphealth.widget.drinksbook;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.content.Context;
import android.content.res.AssetManager;
import android.content.res.Resources;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.hcb.tonguetiphealth.adapter.SelectionListAdapter;
import com.hcb.tonguetiphealth.global.Global;
import com.hcb.tonguetiphealth.manager.JSONManager;
import com.hcb.tonguetiphealth.manager.XmlParserManager;
import com.hcb.tonguetiphealth.model.Drinks;
import com.hcb.tonguetiphealth.model.Province;
import com.hcb.tonguetiphealth.model.User;
import com.hcb.tonguetiphealth.util.HttpUtils;
import com.hcb.tonguetiphealth.util.MessageWhat;
import com.hcb.tonguetiphealth.util.StringUtils;
import com.hcb.tonguetiphealth.view.R;
import com.hcb.tonguetiphealth.widget.GeneralWidget;

public class DrinksBookAddressInfoWidget extends GeneralWidget implements OnClickListener {
	private static final String TAG = "DrinksBookAddressInfoWidget";
	private String url = Global.URL + Global.servlet_wineBuy;
	
	private Activity ctx;
	private Handler mHandler;
	private LinearLayout bt_back;
	private Button bt_sendExpalin, bt_ok;
	private EditText et_address, et_postCode, et_realName, et_tel;
	private TextView et_province, et_city;
	private String province, city, address, postCode, realName, tel;
	private StringBuffer wineId, num;
	private ListView listView;
	private SelectionListAdapter adapter;
	private List<String> strList;
	private boolean isSucceed = false;
	private User user;
	
	private PopupWindow popupWindow;
	private List<Province> provinceList;
	private int position = -1;
	
	public DrinksBookAddressInfoWidget(Context context) {
		super(context);
		ctx = (Activity)context;
		inflate(context, R.layout.drinks_book_address_info, this); 
		user = Global.user;
		
		mHandler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				switch(msg.what) {
				case MessageWhat.SHOW_DIALOG:
					showMessageDialog(ctx, "正在提交订单...");
					break;
				case MessageWhat.DIMISS_DIALOG:
					if(isSucceed) {
						showMessage(ctx, "购买成功");
						Global.cartList.clear();
						ctx.setContentView(new DrinksBookWidget(ctx));
					} else {
						showMessage(ctx, "购买失败");
					}
					bt_ok.setClickable(true);
					dismissMessageDialog();
					break;
				}
			}
		};
		et_province = (TextView)findViewById(R.id.drinks_book_address_info_detail_address1_edittext);
		et_city = (TextView)findViewById(R.id.drinks_book_address_info_detail_address2_edittext);
		et_address = (EditText)findViewById(R.id.drinks_book_address_info_detail_address_edittext);
		et_postCode = (EditText)findViewById(R.id.drinks_book_address_info_postcode_edittext);
		et_realName = (EditText)findViewById(R.id.drinks_book_address_info_real_name_edittext);
		et_tel = (EditText)findViewById(R.id.drinks_book_address_info_tel_num_edittext);
		bt_back = (LinearLayout)findViewById(R.id.drinks_book_back_button);
		bt_sendExpalin = (Button)findViewById(R.id.drinks_book_send_explain_button);
		bt_ok = (Button)findViewById(R.id.drinks_book_cart_commit_buy_button);
		bt_back.setOnClickListener(this);
		bt_sendExpalin.setOnClickListener(this);
		bt_ok.setOnClickListener(this);
		et_province.setOnClickListener(this);
		et_city.setOnClickListener(this);


		initData();

	}
	
	public void onClick(View v) {
		switch(v.getId()) {
		case R.id.drinks_book_address_info_detail_address1_edittext:
			popupWindow = makePopupWindow(ctx, 0);
			popupWindow.showAsDropDown(et_province);
			break;
		case R.id.drinks_book_address_info_detail_address2_edittext:
			popupWindow = makePopupWindow(ctx, 1);
			popupWindow.showAsDropDown(et_city);
			break;
		case R.id.drinks_book_back_button:
			ctx.setContentView(new DrinksBookCartWidget(ctx));
			break;
		case R.id.drinks_book_send_explain_button:
			ctx.setContentView(new DrinksBookSendExplainWidget(ctx));
			break;
		case R.id.drinks_book_cart_commit_buy_button:
			if(isSucceed) {
				showMessage(ctx, "此订单已购买成功");
			} else {
				checkAddress();
			}
			break;
		default:
			break;
		}
	}
	private void checkAddress() {
		province = et_province.getText().toString();
		city = et_city.getText().toString();
		address = et_address.getText().toString();
		postCode = et_postCode.getText().toString();
		realName = et_realName.getText().toString();
		tel = et_tel.getText().toString();
		if(StringUtils.isEmpty(province)) {
			showMessage(ctx, "请选择省份");
			return;
		}
		if(StringUtils.isEmpty(city)) {
			showMessage(ctx, "请选择城市");
			return;
		}
		if(StringUtils.isEmpty(address)) {
			showMessage(ctx, "请填写详细地址");
			return;
		}
		if(StringUtils.isEmpty(postCode)) {
			showMessage(ctx, "请填写邮政编码");
			return;
		}
		if(StringUtils.isEmpty(realName)) {
			showMessage(ctx, "请填写真实姓名");
			return;
		}
		if(StringUtils.isEmpty(tel)) {
			showMessage(ctx, "请填写手机号码");
			return;
		} else {
			if(!IsValidMobileNo(tel)) {
				showMessage(ctx, "请填写正确的手机号码");
				return;
			}
		}
		wineId = new StringBuffer();
		num = new StringBuffer();
		boolean isFirst = true;
		for(Drinks drinks : Global.cartList) {
			if(isFirst) {
				isFirst = false;
				wineId.append(drinks.getId());
				num.append(drinks.getNum());
			} else {
				wineId.append("," + drinks.getId());
				num.append("," + drinks.getNum());
			}
			System.out.println("--------- id: " + drinks.getId() + " num: " + drinks.getNum());
		}

		bt_ok.setClickable(false);
		mHandler.sendEmptyMessage(MessageWhat.SHOW_DIALOG);
		new Thread() {
			public void run() {
				String response = null;
				try {
					List <NameValuePair> params = new ArrayList <NameValuePair>();
					params.add(new BasicNameValuePair("user", user.getUserName()));
					params.add(new BasicNameValuePair("wineId", wineId.toString()));
					params.add(new BasicNameValuePair("num", num.toString()));
					params.add(new BasicNameValuePair("province", province));
					params.add(new BasicNameValuePair("city", city));
					params.add(new BasicNameValuePair("address", address));
					params.add(new BasicNameValuePair("postCode", postCode));
					params.add(new BasicNameValuePair("realName", realName));
					params.add(new BasicNameValuePair("tel", tel));
					response = HttpUtils.Post(url, params);
					
					if(Global.DEBUG) {
						System.out.println("-----------------------------\n" + response);
					}
				} catch(Exception e) {
					Log.e(TAG, "Exception", e);
				}
				if(!StringUtils.isEmpty(response)) {
					JSONManager jManager = new JSONManager();
					boolean isGotJSONObject = jManager.isGotJSONObject(response);
					if(isGotJSONObject) {
						isSucceed = true;
						int count = jManager.getResult();
						String msg = jManager.getMsg();
						System.out.println("------ 得到msg: " + count + ":" + msg);
					}
				}
				mHandler.sendEmptyMessage(MessageWhat.DIMISS_DIALOG);
			}
		}.start();
	}
	private void initData() {
		strList = new ArrayList<String>();
		et_realName.setText(user.getRealName());
		et_tel.setText(user.getTel());
		et_province.setText(user.getProvince());
		city = user.getCity();
		if(!StringUtils.isEmpty(city)) {
			et_city.setText(city);
			et_city.setVisibility(TextView.VISIBLE);
		}
	}
	
	private void initDataOfProvinceOrCity(int flag) {
		AssetManager assetManager = ctx.getAssets();
		InputStream inputStream = null; 
		if(0 == flag) {
			try { 
			   inputStream = assetManager.open("provinces.xml"); 
			   provinceList = XmlParserManager.getProvinces(inputStream);
			   strList.clear();
			   for(Province p : provinceList) {
				   strList.add(p.getName());
			   }
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else if(1 == flag) {
			try { 
				if(-1 == position) {
					inputStream = assetManager.open("provinces.xml"); 
				    provinceList = XmlParserManager.getProvinces(inputStream);
				    strList.clear();
				    for(int i=0; i<provinceList.size(); i++) {
					   if(user.getProvince().contains(provinceList.get(i).getName())) {
						   position = i;
						   break;
					   }
				    }
				}
			   String tagCity = "city_" + position +".xml";
			   inputStream = assetManager.open(tagCity); 
			   strList = XmlParserManager.getCitys(inputStream);
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			
		}
	}
	private void setCityVisibility(boolean visible) {
		//设置city是否可选
		if(visible) {
			et_city.setText("");
			et_city.setVisibility(TextView.VISIBLE);
		} else {
			et_city.setVisibility(TextView.INVISIBLE);
		}
	}
	//创建一个包含自定义view的PopupWindow
	private PopupWindow makePopupWindow(Context cx, final int flag) {
	    PopupWindow window;
	    window = new PopupWindow(cx);
	    
	    LayoutInflater li = LayoutInflater.from(ctx); 
        View view = li.inflate(R.layout.drinks_book_dialog_list, null); 
        listView = (ListView)view.findViewById(R.id.drinks_book_dialog_listview);
        initDataOfProvinceOrCity(flag);
        adapter = new SelectionListAdapter(ctx, strList);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				position = arg2;
				String result = (String)arg0.getAdapter().getItem(arg2);
				if(0 == flag) {
					et_province.setText(result);
					setCityVisibility(provinceList.get(arg2).isHasCitys());
				} else if(1 == flag) {
					et_city.setText(result);
				} else {
					
				}
				
				popupWindow.dismiss();
			}
		});
	    
	    final Resources res = cx.getResources();
	    view.setBackgroundColor(res.getColor(R.color.transparent2));
	    view.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
	            LayoutParams.WRAP_CONTENT));
	    //设置PopupWindow显示和隐藏时的动画
	    window.setAnimationStyle(R.style.AnimationFade);
	    //设置PopupWindow的大小（宽度和高度）
	    window.setWidth(et_city.getWidth());
	    //window.setWidth(res.getDimensionPixelSize(R.dimen.page_window_width));
	    window.setHeight(res.getDimensionPixelSize(R.dimen.page_window_height));
	    //设置PopupWindow的内容view
	    window.setContentView(view);
        //设置PopupWindow外部区域是否可触摸
        window.setOutsideTouchable(true);
        //设置焦点，必须设置，否则listView无法响应
        window.setFocusable(true);
        window.update();
        
	    return window;
	}
	@Override
	public void notifyAdapter() {
		
	}
}
